/*
 * @Author: your name
 * @Date: 2020-09-01 10:59:27
 * @LastEditTime: 2020-09-14 15:20:35
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \admin-management\web\src\utils\axios.js
 */
import axios from 'axios';

import { message } from 'ant-design-vue';

import store from '../store/index';
import router from '../router/index';

import { BASE_URL } from './config';

let loadingCount = 0;
let errorMsg = null;
const service = axios.create({
  baseURL: BASE_URL + '/admin_api.php',
  timeout: 10000
});

service.interceptors.request.use(
  (config) => {
    store.dispatch('CHANGE_LOAD', true);
    loadingCount++;
    if (store.state.token) {
      config.headers.Authorization = store.state.token;
    }
    return config;
  },
  (error) => {
    loadingCount--;
    if (loadingCount <= 0) {
      loadingCount = 0;
      store.dispatch('CHANGE_LOAD', false);
    }
    console.log('error :', error);
    return Promise.reject(error);
  }
);

service.interceptors.response.use(
  (response) => {
    loadingCount--;
    if (loadingCount <= 0) {
      loadingCount = 0;
      store.dispatch('CHANGE_LOAD', false);
    }
    if (response.status === 200 && response.data.code === -2) {
      if (errorMsg) {
        return;
      }
      errorMsg = message.error(response.data.msg);
      setTimeout(() => {
        errorMsg = null;
      }, 1000);
      router.replace({
        name: 'Login'
      });
      store.commit('CLEAR_CACHE');
      return;
    }
    return response;
  },
  (error) => {
    store.dispatch('CHANGE_LOAD', false);
    loadingCount = 0;
    console.dir(error);
    if (!error.response) {
      message.error(error.message);
    }
    return Promise.reject(error);
  }
);

export default {
  get: (url, params = {}, config = {}) => {
    return new Promise((resolve, reject) => {
      service
        .get(url, {
          params,
          ...config
        })
        .then(
          (response) => {
            if (response.data.code <= 0) {
              message.error(response.data.msg);
              reject(response.data);
            }
            resolve(response.data);
          },
          (err) => {
            reject(err);
          }
        );
    });
  },
  post: (url, params = {}, config = {}) => {
    return new Promise((resolve, reject) => {
      service.post(url, params, config).then(
        (response) => {
          if (response.data.code <= 0) {
            message.error(response.data.msg);
            reject(response.data);
          }
          resolve(response.data);
          return;
        },
        (err) => {
          reject(err);
        }
      );
    });
  }
};
